package com.matt.service.impl;

import com.matt.domain.NurseVideo;
import com.matt.repository.NurseVideoRepository;
import com.matt.service.NurseVideoService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Describle This Class Is
 * @Author ZengMin
 * @Date 2018/12/12 16:55
 * @Company Matt
 */
@Service
public class NurseVideoServiceImpl implements NurseVideoService {

    @Autowired
    NurseVideoRepository nurseVideoRepository;

    @Override
    public Page<NurseVideo> getPageList(Integer pageNum, Integer pageSize) {
        Specification<NurseVideo> specification = new Specification<NurseVideo>() {
            @Override
            public Predicate toPredicate(Root<NurseVideo> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();

                predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("deleted"),false )));
                query.where(predicates.toArray(new Predicate[predicates.size()]));
                query.orderBy(criteriaBuilder.asc(root.get("type")));
                return query.getRestriction();
            }
        };
        Page<NurseVideo> nurseVideoPage = nurseVideoRepository.findAll(specification, PageRequest.of(pageNum, pageSize));
        List<NurseVideo> list = Lists.newArrayList();
        nurseVideoPage.getContent().stream().forEach(o -> {
            list.add(o);
        });

        return new PageImpl(list, PageRequest.of(pageNum, pageSize), nurseVideoPage.getTotalElements());
    }

    @Override
    public NurseVideo getById(String videoId) {
        return nurseVideoRepository.getOne(videoId);
    }
}
